<template>
  <div class="staff">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold">人员管理</span>
      </div>
      <!-- 查询表单 -->
      <el-row>
        <el-col :span="24">
          <el-form inline class="query-form">
            <el-form-item label="员工编号">
              <el-input
                v-model="query.employeeId"
                placeholder="请输入员工编号"
              ></el-input>
            </el-form-item>
            <el-form-item label="员工名称">
              <el-input
                v-model="query.employeeName"
                placeholder="请输入员工名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="商店编码">
              <el-input
                v-model="query.storeId"
                placeholder="请输入商店编码"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <!-- 操作按钮 -->
      <el-row>
        <el-col :span="24">
          <el-button type="success" @click="handleAdd" class="add-button"
            >新增员工</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格展示 -->
      <el-row>
        <el-col :span="24">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            class="staff-table"
          >
            <el-table-column
              prop="employeeId"
              label="员工编号"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="employeeName"
              label="员工名称"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="age"
              label="员工年龄"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="position"
              label="员工职务"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="hireDate"
              label="入职时间"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="storeId"
              label="商店编码"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="storeName"
              label="商店名称"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页组件 -->
      <el-row>
        <el-col :span="24">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="staffForm"
        :model="staffForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="员工编号">
          <el-input
            v-model="staffForm.employeeId"
            placeholder="请输入员工编号"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="员工名称" prop="employeeName">
          <el-input
            v-model="staffForm.employeeName"
            placeholder="请输入员工名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="员工年龄" prop="age">
          <el-input
            v-model.number="staffForm.age"
            placeholder="请输入员工年龄"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="员工薪资"
          v-if="dialogTitle === '新增员工'"
          prop="salary"
        >
          <el-input
            v-model.number="staffForm.salary"
            placeholder="请输入员工薪资"
          ></el-input>
        </el-form-item>
        <el-form-item label="员工职务" prop="position">
          <el-input
            v-model="staffForm.position"
            placeholder="请输入员工职务"
          ></el-input>
        </el-form-item>
        <el-form-item label="入职时间" prop="hireDate">
          <el-date-picker
            style="float: left"
            v-model="staffForm.hireDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="商店编码" prop="storeId">
          <el-select
            v-model="staffForm.storeId"
            placeholder="请选择商店"
            @change="onStoreChange"
            style="float: left"
          >
            <el-option
              v-for="store in stores"
              :key="store.storeId"
              :label="store.storeId"
              :value="store.storeId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商店名称">
          <el-input v-model="staffForm.storeName" disabled></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStaff">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { deleteEmp, empCreate, empEdit, empPageQuery } from "@/api/empApi";
import { getAllStore } from "@/api/storeApi";
import axios from "axios";

export default {
  name: "AdminStaff",
  data() {
    return {
      query: {
        employeeId: "",
        employeeName: "",
        storeId: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      dialogTitle: "新增员工",
      staffForm: {
        employeeId: "",
        employeeName: "",
        age: "",
        salary: "",
        position: "",
        hireDate: "",
        storeId: "",
        storeName: "",
      },
      currentStaff: null,
      stores: [], // 存储从后端获取的商店列表
      rules: {
        employeeName: [
          { required: true, message: "请输入员工名称", trigger: "blur" },
        ],
        age: [
          { required: true, message: "请输入员工年龄", trigger: "blur" },
          { type: "number", message: "员工年龄必须为数字", trigger: "blur" },
        ],
        salary: [
          { required: true, message: "请输入员工薪资", trigger: "blur" },
          { type: "number", message: "员工薪资必须为数字", trigger: "blur" },
        ],
        position: [
          { required: true, message: "请输入员工职务", trigger: "blur" },
        ],
        hireDate: [
          { required: true, message: "请选择入职时间", trigger: "change" },
        ],
        storeId: [{ required: true, message: "请选择商店", trigger: "change" }],
      },
    };
  },
  methods: {
    fetchData() {
      const params = {
        query: {
          employeeId: this.query.employeeId,
          employeeName: this.query.employeeName,
          storeId: this.query.storeId,
        },
        pageRequestDto: {
          page: this.currentPage,
          size: this.pageSize,
        },
      };

      empPageQuery(params)
        .then((res) => {
          this.tableData = res.data.records || [];
          this.total = res.data.total || 0;
        })
        .catch((error) => {
          console.error("Error fetching staff data:", error);
          this.$message.error("加载员工数据失败");
        });
    },
    resetQuery() {
      this.query.employeeId = "";
      this.query.employeeName = "";
      this.query.storeId = "";
      this.fetchData();
    },
    handleAdd() {
      this.dialogTitle = "新增员工";
      this.staffForm = {
        employeeId: "",
        employeeName: "",
        age: "",
        position: "",
        hireDate: "",
        storeId: "",
        storeName: "",
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑员工";
      this.currentStaff = row;
      this.staffForm = { ...row };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm(`确定要删除员工 ${row.employeeId} 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteEmp(row.employeeId)
            .then((res) => {
              this.$message.success("删除成功");
              this.fetchData();
            })
            .catch((error) => {
              console.error("Error deleting staff:", error);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    saveStaff() {
      this.$refs.staffForm.validate((valid) => {
        if (valid) {
          if (this.dialogTitle === "新增员工") {
            empCreate(this.staffForm)
              .then((res) => {
                this.$message.success("新增成功");
                this.fetchData();
                this.dialogVisible = false;
              })
              .catch((error) => {
                console.error("Error adding staff:", error);
                this.$message.error("新增失败");
              });
          } else {
            empEdit(this.staffForm.employeeId, this.staffForm)
              .then((response) => {
                this.$message.success("编辑成功");
                this.fetchData();
                this.dialogVisible = false;
              })
              .catch((error) => {
                console.error("Error updating staff:", error);
                this.$message.error("编辑失败");
              });
          }
        } else {
          this.$message.error("表单验证失败，请检查输入信息");
          return false;
        }
      });
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    onStoreChange(storeId) {
      const selectedStore = this.stores.find(
        (store) => store.storeId === storeId
      );
      if (selectedStore) {
        this.staffForm.storeName = selectedStore.storeName;
      }
    },
    fetchStores() {
      getAllStore()
        .then((res) => {
          this.stores = res.data || [];
        })
        .catch((error) => {
          console.error("Error fetching stores:", error);
          this.$message.error("加载商店数据失败");
        });
    },
  },
  mounted() {
    this.fetchData();
    this.fetchStores(); // 获取商店列表
  },
};
</script>

<style scoped>
.staff {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.query-form {
  margin-bottom: 20px;
}

.staff-table {
  margin-top: 20px;
}

.add-button {
  float: left; /* 将按钮置于左侧 */
}
</style>